/********************************************************************************
 * Project Name		[JavaEE_Web]
 * File Name     	[UserDao.java]
 * Creation Date 	[2015-01-01]
 * 
 * Copyright© ge.y.yang@gmail.com All Rights Reserved
 * 
 * Work hard, play harder, think big and keep fit
 ********************************************************************************/
package filter.acl.dao;

import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import filter.acl.bean.Authority;
import filter.acl.bean.User;

/**
 * @author 不落的太阳(Sean Yang aka ShortPeace)
 * @version 1.0
 * @since jdk 1.8
 * 
 */
public class UserDao {

	private static Map<String, User> users = new HashMap<>();
	private static List<Authority> authorities = new ArrayList<>();

	static {
		initiateUser(new String[] { "page-1", "page-2" }, new String[] { "/jsp/acl/1.jsp", "/jsp/acl/2.jsp" }, "Sean");
		initiateUser(new String[] { "page-3", "page-4" }, new String[] { "/jsp/acl/3.jsp", "/jsp/acl/4.jsp" }, "Yang");
		if (authorities != null) {
			Collections.sort(authorities, new Comparator<Authority>() {
				@Override
				public int compare(Authority a1, Authority a2) {
					return a1.getDisplayName().compareTo(a2.getDisplayName());
				}
			});
		}
	}

	private static void initiateUser(String[] displayNames, String[] urls, String username) {
		if (displayNames.length != urls.length) {
			return;
		}
		List<Authority> tempAuthorities = new ArrayList<>();
		for (int i = 0; i < displayNames.length; i++) {
			Authority authority = new Authority();
			authority.setDisplayName(displayNames[i]);
			authority.setUrl(urls[i]);
			tempAuthorities.add(authority);
			if (!authorities.contains(authority)) {
				authorities.add(authority);
			}
		}

		User user = new User();
		user.setUsername(username);
		user.setAuthorities(tempAuthorities);

		users.put(username, user);
	}

	public User getUser(String username) {
		return users.get(username);
	}

	public void update(String username, List<Authority> authorities) {
		User user = users.get(username);
		user.getAuthorities().clear();
		user.setAuthorities(authorities);
	}

	public List<Authority> getAuthorities() {
		return authorities;
	}

	public List<Authority> getAuthorities(String[] urls) {
		List<Authority> tempAuthorities = new ArrayList<>();

		for (Authority authority : authorities) {
			if (urls != null) {
				for (String url : urls) {
					if (url.equals(authority.getUrl())) {
						tempAuthorities.add(authority);
					}
				}
			}
		}
		return tempAuthorities;
	}
}
